// file-upload.service.ts
import { Inject, Injectable } from '@nestjs/common';
import { promises as fs } from 'fs';
import { join } from 'path';
import { PrismaService } from 'src/prisma.service';
import { CustomeFile } from './entities/file-upload.entity';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class FileUploadService {
  @Inject(ConfigService)
  configService: ConfigService;
  @Inject()
  prismaService: PrismaService;
  async handleFileUpload(
    file: Express.Multer.File,
    userId: number,
  ): Promise<CustomeFile> {
    // 不存在uploads文件夹的话，则创建
    if (
      !(await fs.stat(join(__dirname, '..', '..', 'uploads'))).isDirectory()
    ) {
      await fs.mkdir(join(__dirname, '..', '..', 'uploads'), {
        recursive: true,
      });
    }
    const newFileName = `${+new Date()}-${userId}-${file.originalname}`;
    // 如果存在对应的文件，则覆盖
    const uploadPath = join(__dirname, '..', '..', 'uploads', newFileName); // 指定上传路径
    await fs.writeFile(uploadPath, file.buffer); // 这里以 Buffer 的形式保存文件
    // 存储到数据库
    const res = await this.prismaService.file.create({
      data: {
        name: newFileName,
        path: uploadPath,
        fileType: file.mimetype,
        uploadedBy: userId,
        href: `${this.configService.get('FILE_ACCESS_PATH')}/${newFileName}`,
      },
      // include: { user: true, avatarUser: false },
    });
    return res; // 返回相关信息
  }
  async getFileList(): Promise<CustomeFile[]> {
    return this.prismaService.file.findMany({
      where: {
        isDeleted: false,
      },
    });
  }
}
